// 设置文件
// import setting from "@/setting.js";
import { cloneDeep } from "lodash";
import fetchMenuData from "@/api/localMenu";
import { frameInRoutes } from "@/router/routes";
import purchaseIn from "@/router/modules/purchaseIn";
import sale from "@/router/modules/sale";

const localMenu = [
  {
    title: "采购",
    path: "/purchaseIn",
    children: [purchaseIn].map(item => {
      return {
        title: item.title,
        path: item.path,
        children: item.children.map(subItem => {
          return {
            title: subItem.title,
            path: subItem.fullPath
          };
        })
      };
    })
  },
  {
    title: "销售",
    path: "/sale",
    children: [sale].map(item => {
      return {
        title: item.title,
        path: item.path,
        children: item.children.map(subItem => {
          return {
            title: subItem.title,
            path: subItem.fullPath
          };
        })
      };
    })
  }
];

//本地支持的所有头部菜单
const localHeader = localMenu.map(item => {
  return {
    title: item.title,
    path: item.path
  };
});

const localAsideMenu = cloneDeep(localMenu);

export default {
  namespaced: true,
  state: {
    //从服务端返回的菜单树
    remoteMenu: null,
    // 顶栏菜单
    header: [],
    // 侧栏菜单
    aside: [],
    // 侧边栏收缩
    asideCollapse: false
  },
  actions: {
    //获取远程的菜单数据
    async getRemoteMenu({ state, commit }) {
      //fetchMenuData 菜单数据在实际使用的过程当中从API接口获取
      if (!fetchMenuData || fetchMenuData.length === 0) {
        //获取到的远程菜单为空
        commit("remoteMenuSet", []);
        commit("asideSet", []);
        return Promise.resolve([]);
      } else {
        const renderHeader = localHeader.filter(item => fetchMenuData.map(item => item.name).includes(item.title)); //实际渲染的头部菜单
        const validMenuData = fetchMenuData.filter(item => localHeader.map(item => item.title).includes(item.name)); //第一次取头部（一级）菜单下的所有二级和三级子菜单
        const renderMenu = validMenuData.map(remoteItem => {
          const localItem = localAsideMenu.find(obj => obj.title == remoteItem.name);
          const renderMenuItem = remoteItem.children.map(remoteChildItem => {
            const localChildItem = localItem.children.find(obj => obj.title == remoteChildItem.name);
            if (remoteChildItem.children) {
              const children = [];
              remoteChildItem.children.map(lastRemoteItem => {
                if (localChildItem) {
                  const lastLocalItem = localChildItem.children.find(obj => obj.title == lastRemoteItem.name);
                  lastLocalItem && children.push(lastLocalItem);
                }
              });
              return { title: remoteChildItem.name, icon: "", children };
            } else {
              return { title: remoteChildItem.name, icon: "" };
            }
          });
          return {
            title: remoteItem.name,
            children: renderMenuItem,
            path: localItem.path
          };
        });
        commit("remoteMenuSet", renderMenu);
        commit("headerSet", renderHeader);
        commit("asideSet", renderMenu[0].children);
        commit("d2admin/page/init", frameInRoutes, {
          root: true
        });
        return Promise.resolve(renderMenu);
      }
    },
    /**
     * 设置侧边栏展开或者收缩
     * @param {Object} state vuex state
     * @param {Boolean} collapse is collapse
     */
    asideCollapseSet({ state, dispatch }, collapse) {
      return new Promise(async resolve => {
        // store 赋值
        state.asideCollapse = collapse;
        // 持久化
        await dispatch(
          "d2admin/db/set",
          {
            dbName: "sys",
            path: "menu.asideCollapse",
            value: state.asideCollapse,
            user: true
          },
          { root: true }
        );
        // end
        resolve();
      });
    },
    /**
     * 切换侧边栏展开和收缩
     * @param {Object} state vuex state
     */
    asideCollapseToggle({ state, dispatch }) {
      return new Promise(async resolve => {
        // store 赋值
        state.asideCollapse = !state.asideCollapse;
        // 持久化
        await dispatch(
          "d2admin/db/set",
          {
            dbName: "sys",
            path: "menu.asideCollapse",
            value: state.asideCollapse,
            user: true
          },
          { root: true }
        );
        // end
        resolve();
      });
    },
    /**
     * 从持久化数据读取侧边栏展开或者收缩
     * @param {Object} state vuex state
     */
    asideCollapseLoad({ state, dispatch }) {
      return new Promise(async resolve => {
        // store 赋值
        state.asideCollapse = await dispatch(
          "d2admin/db/get",
          {
            dbName: "sys",
            path: "menu.asideCollapse",
            // defaultValue: setting.menu.asideCollapse,
            defaultValue: false,
            user: true
          },
          { root: true }
        );
        // end
        resolve();
      });
    },

    /**
     * 动态切换左侧菜单栏
     * @param state
     * @param commit
     * @param path
     */
    switchAsideMenu({ dispatch, state, commit }, fullPath) {
      const remoteMenu = state.remoteMenu;
      const commitAsideSet = shortPath => {
        remoteMenu.find(item => item.path === shortPath) && commit("asideSet", remoteMenu.find(item => item.path === shortPath).children);
      };
      if (fullPath.startsWith("/purchaseIn")) {
        commitAsideSet("/purchaseIn");
      } else if (fullPath.startsWith("/sale")) {
        commitAsideSet("/sale");
      } else if (fullPath.startsWith("/stock")) {
        commitAsideSet("/stock");
      } else if (fullPath.startsWith("/mallManage")) {
        commitAsideSet("/mallManage");
      } else if (fullPath.startsWith("/paymentReceipt")) {
        commitAsideSet("/paymentReceipt");
      } else if (fullPath.startsWith("/financial")) {
        commitAsideSet("/financial");
      } else if (fullPath.startsWith("/goldGarment")) {
        commitAsideSet("/goldGarment");
      } else if (fullPath.startsWith("/report")) {
        commitAsideSet("/report");
      } else if (fullPath.startsWith("/userSystem")) {
        commitAsideSet("/userSystem");
      } else if (fullPath.startsWith("/setting")) {
        commitAsideSet("/setting");
      } else if (fullPath.startsWith("/download")) {
        commitAsideSet("/download");
      }
    }
  },
  mutations: {
    /**
     * @description 设置顶栏菜单
     * @param {Object} state vuex state
     * @param {Array} menu menu setting
     */
    headerSet(state, menu) {
      // store 赋值
      state.header = menu;
    },
    /**
     * @description 设置侧边栏菜单
     * @param {Object} state vuex state
     * @param {Array} menu menu setting
     */
    asideSet(state, menu) {
      // store 赋值
      state.aside = menu;
    },
    /**
     * @description 设置从服务端返回的菜单树
     * @param {Object} state vuex state
     * @param {Array} menu menu setting
     */
    remoteMenuSet(state, dataList) {
      // store 赋值
      state.remoteMenu = dataList;
    }
  }
};
